<template>
  <van-row class="center">
    <div class="animate__animated animate__flipInY" style="padding: 10rem 0">
      <van-image width="80%" :src="require('../../assets/logo.png')"/>
      <div>
<!--        <h2 style="color: black">远昌管家</h2>-->
        <van-form
          style="padding: 2rem;"
          error-message-align="center"
          @submit="onSubmit"
        >
          <van-field
              left-icon="user"
            v-model="username"
            name="username"
            placeholder="账号"
            :rules="[{ required: true, message: '请填写账号' }]"
          />
          <van-field
              left-icon="lock"
            v-model="password"
            style="margin-top: 1em"
            type="password"
            name="password"
            placeholder="密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
          <van-field name="switch" style="margin-top: 1em">
            <template #input>
              <!--<van-switch v-model="rememberMe" size="20"/>-->
              <van-checkbox v-model="rememberMe">记住我</van-checkbox>
            </template>
          </van-field>
          <div style="margin-top: 1em;">
            <van-button
              round
              block
              type="info"
              native-type="submit"
              :loading="loginLoading"
              :disabled="loginLoading"
            >登录
            </van-button>
          </div>
        </van-form>
      </div>
    </div>
  </van-row>
</template>

<script>
export default {
  name: 'Index',
  data() {
    return {
      username: localStorage.username || '',
      password: localStorage.password || '',
      loginLoading: false,
      rememberMe: localStorage.rememberMe || false,
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    },
    rememberMe(val, ol) {
      if (val) {
        localStorage.rememberMe = true
        localStorage.username = this.username
        localStorage.password = this.password
      }
    }
  },
  methods: {
    onSubmit(values) {
      const _this = this
      _this.loginLoading = true
      this.$store.dispatch('user/login', values).then(resp => {
        if (resp.success) {
          this.$store.dispatch('user/getInfo', resp.data).then(res => {
            this.$router.push({ path: this.redirect || '/' })
            _this.loginLoading = false
          })
        } else {
          _this.loginLoading = false
        }
      })
    }
  }
}
</script>

<style scoped>
    .van-field {
        background-color: transparent !important;
    }
</style>
